#import "NSString+Helper.h"
#import <sys/utsname.h>


@implementation NSString (Helper)
#pragma mark - 返回当APP版本
+ (NSString *)getAppVer {
    if(UserValue(@"rsa_app_ver")) {
        NSDictionary *dict = (NSDictionary *)UserValue(@"rsa_app_ver");
        return dict[@"verApp"];
    } else {
        NSLog(@"w9skdausdkads --- - asda %@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]);
        return (NSString *)[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    }
}

#pragma mark 是否空字符串
- (BOOL)isEmptyString {
    if (![self isKindOfClass:[NSString class]]) {
        return TRUE;
    }else if (self==nil) {
        return TRUE;
    }else if(!self) {
        // null object
        return TRUE;
    } else if(self==NULL) {
        // null object
        return TRUE;
    } else if([self isEqualToString:@"NULL"]) {
        // null object
        return TRUE;
    }else if([self isEqualToString:@"(null)"]){
        
        return TRUE;
    }else{
        //  使用whitespaceAndNewlineCharacterSet删除周围的空白字符串
        //  然后在判断首位字符串是否为空
        NSString *trimedString = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if ([trimedString length] == 0) {
            // empty string
            return TRUE;
        } else {
            // is neither empty nor null
            return FALSE;
        }
    }
}

#pragma mark 判断是否是手机号
- (BOOL)checkTel {
    NSString *regex = @"^((13[0-9])|(14[0-9])|(17[0-9])|(15[0-9])|(18[0-9]))\\d{8}$";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [pred evaluateWithObject:self];
}

#pragma mark 判断是否为index位纯数字字符串
+ (BOOL)isPureNumandCharacters:(NSString *)string withlimit:(NSInteger)index
{
    if(string.length == index) {
        string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
        if(string.length > 0)
        {
            return NO;
        }
        return YES;
    } else {
        return NO;
    }
}

///判断是够是数字
+ (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}


#pragma mark 判断是否是邮箱
- (BOOL)isValidateEmail {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

#pragma mark 清空字符串中的空白字符
- (NSString *)trimString {
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

#pragma mark 返回沙盒中的文件路径
+ (NSString *)stringWithDocumentsPath:(NSString *)path {
    NSString *file = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    return [file stringByAppendingPathComponent:path];
}

#pragma mark 写入系统偏好
- (void)saveToNSDefaultsWithKey:(NSString *)key {
    [[NSUserDefaults standardUserDefaults] setObject:self forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark 一串字符在固定宽度下，正常显示所需要的高度 method
+ (CGFloat)autoHeightWithString:(NSString *)string Width:(CGFloat)width Font:(UIFont *)font {
    
    //大小
    CGSize boundRectSize = CGSizeMake(width, MAXFLOAT);
    //绘制属性（字典）
    NSDictionary *fontDict = @{ NSFontAttributeName: font };
    //调用方法,得到高度
    CGFloat newFloat = [string boundingRectWithSize:boundRectSize
                                            options: NSStringDrawingUsesLineFragmentOrigin
                        | NSStringDrawingUsesFontLeading
                                         attributes:fontDict context:nil].size.height;
    return newFloat;
}

#pragma mark 一串字符在一行中正常显示所需要的宽度 method
+ (CGFloat)autoWidthWithString:(NSString *)string Font:(UIFont *)font {
    
    //大小
    CGSize boundRectSize = CGSizeMake(MAXFLOAT, font.lineHeight);
    //绘制属性（字典）
    NSDictionary *fontDict = @{ NSFontAttributeName: font };
    //调用方法,得到高度
    CGFloat newFloat = [string boundingRectWithSize:boundRectSize
                                            options: NSStringDrawingUsesLineFragmentOrigin
                        | NSStringDrawingUsesFontLeading
                                         attributes:fontDict context:nil].size.width;
    return newFloat;
}

+ (NSAttributedString *)makeDeleteLine:(NSString *)string{
    string = [NSString stringWithFormat:@"<html><body style =\"font-size:12px;\"><s><font color=\"#B6B6B6\">%@</font></s></body></html>",string];
    NSAttributedString * attributeString = [[NSAttributedString alloc]initWithData:[string dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
    return attributeString;
}




+ (BOOL)validatePassword:(NSString *)password {
    NSString *passWordRegex = @"(\\d+[a-zA-Z]+[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*)|([a-zA-Z]+\\d+[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*)|(\\d+[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*[a-zA-Z]+)|([a-zA-Z]+[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*\\d+)|([-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*\\d+[a-zA-Z]+)|([-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]*[a-zA-Z]+\\d+)";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", passWordRegex];
    if(password.length >= 6 && password.length <= 16) {
        if([passWordPredicate evaluateWithObject:password]) {
            return YES;
        } else {
            return NO;
        }
    } else {
        return NO;
    }
}


+ (NSString *)StringHaveNextLine:(NSArray *)array{
    NSString *lineString;
//    for (NSInteger index = 0; index < array.count; index ++) {
//        ZJPFriendInfoBrandList *infoBrand = array[index];
//        if (index == 0) {
//            lineString = [NSString stringWithFormat:@"%@",infoBrand.brandCNName];
//        }else{
//            lineString = [NSString stringWithFormat:@"%@\n%@",lineString,infoBrand.brandCNName];
//        }
//        
//    }
    return lineString;
}

+ (NSString *)getJsonStringWithDic:(NSDictionary *)dic {
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return str;
}

+ (NSString *)getJsonStringWithArr:(NSArray *)arr {
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:nil];
    NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return str;
}


+ (NSString *)getCurrentTime {
    NSDateFormatter *fomatter = [[NSDateFormatter alloc] init];
    [fomatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//    NSString *dateString = [fomatter stringFromDate:[NSDate date]];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
    return timeSp;
}

////判断当前字符串是6位纯数字
//+ (BOOL)isPureInt:(NSString *)string {
//    if(string.length == 6) {
//        NSScanner* scan = [NSScanner scannerWithString:string];
//        int val;
//        return [scan scanInt:&val] && [scan isAtEnd];
//    } else {
//        return NO;
//    }
//}

//不带历史订单的返回
+ (NSString *)stringPraseWithPersonalArray:(NSArray *)indexArr {
    NSArray *nameArr = @[@"收派员",@"集结点",@"支线",@"BD"];
    NSMutableArray *returnArray = [NSMutableArray array];
    
    BOOL flag = YES;
    for(NSString *indexString in indexArr) {
        if([indexString integerValue] >= 4) {
            flag = NO;
        }
    }
    NSString *newStr;
    if(flag) {
        for(NSInteger i = 0 ; i < indexArr.count ; i ++) {
            NSString *index = indexArr[i];
            NSInteger sharedIndex = [index integerValue];
            NSString *nameString = nameArr[sharedIndex];
            [returnArray addObject:nameString];
        }
        newStr = [returnArray componentsJoinedByString:@","];
    } else {
       newStr = @"您暂时没有工种信息";
    }
//    for(NSInteger i = 0 ; i < indexArr.count ; i ++) {
//        NSString *index = indexArr[i];
//        NSInteger sharedIndex = [index integerValue];
//        NSString *nameString = nameArr[sharedIndex];
//        [returnArray addObject:nameString];
//    }
//    NSString *newStr = [returnArray componentsJoinedByString:@","];
    return newStr;
}


//phoneType
+ (NSString *)iphoneType {
    
    struct utsname systemInfo;
    uname(&systemInfo);
    
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
    
    if ([platform isEqualToString:@"iPod1,1"])  return @"iPod Touch 1G";
    
    if ([platform isEqualToString:@"iPod2,1"])  return @"iPod Touch 2G";
    
    if ([platform isEqualToString:@"iPod3,1"])  return @"iPod Touch 3G";
    
    if ([platform isEqualToString:@"iPod4,1"])  return @"iPod Touch 4G";
    
    if ([platform isEqualToString:@"iPod5,1"])  return @"iPod Touch 5G";
    
    if ([platform isEqualToString:@"iPad1,1"])  return @"iPad 1G";
    
    if ([platform isEqualToString:@"iPad2,1"])  return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,2"])  return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,3"])  return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,4"])  return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,5"])  return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad2,6"])  return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad2,7"])  return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad3,1"])  return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,2"])  return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,3"])  return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,4"])  return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad3,5"])  return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad3,6"])  return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad4,1"])  return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,2"])  return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,3"])  return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,4"])  return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"iPad4,5"])  return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"iPad4,6"])  return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    
    return platform;
    
}

#pragma mark -_- dataOperation
+ (NSString *)getAuthcode
{
    
    NSInteger kCharCount = 16;
    
    NSArray *dataArr = [[NSArray alloc] initWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",nil];
    
    NSString *authCodeStr = [[NSMutableString alloc] initWithCapacity:kCharCount];
    
    for (int i = 0; i < kCharCount; i++)
    {
        NSInteger index = arc4random() % (dataArr.count-1);
        NSString *tempStr = [dataArr objectAtIndex:index];
        authCodeStr = (NSMutableString *)[authCodeStr stringByAppendingString:tempStr];
    }
    return authCodeStr;
}


+ (NSString *)codeBaseStringWithString:(NSString *)codeString
{
    NSString *newString = [NSString getAuthcode];
    NSString *cString = [Base64 stringByEncodingData:[codeString dataUsingEncoding:NSUTF8StringEncoding]];
    NSMutableString *muString = [NSMutableString stringWithString:cString];
    [muString insertString:newString atIndex:2];
    NSString *doubleCString = [NSString stringWithFormat:@"%@",muString];
    return doubleCString;
   
}

+ (NSString *)decodeBaseStringWithString:(NSString *)decodeString
{
    NSMutableString *muString = [NSMutableString stringWithString:decodeString];
    [muString deleteCharactersInRange:NSMakeRange(2, 16)];
    NSString *dString = [NSString stringWithFormat:@"%@",muString];
    NSData *deCodeData = [Base64 decodeString:dString];
    NSString *reDecodeString = [[NSString alloc] initWithData:deCodeData encoding:NSUTF8StringEncoding];
    return reDecodeString;
}


+ (BOOL)CheckExitsWithName:(NSString *)name
{
    NSMutableDictionary *infoDic;
    if(UserValue(@"namePsdInfo")) {
        infoDic = [NSMutableDictionary dictionaryWithDictionary:UserValue(@"namePsdInfo")];
        NSString *psdString = infoDic[name];
        if(psdString && psdString.length != 0) {
            return YES;
        } else {
            return NO;
        }
    } else {
        
        return NO;
    }
}


+ (void)addNameInfoWithDict:(NSString *)nameString andPassWord:(NSString *)passWordSting
{
    NSString *codeString = [NSString codeBaseStringWithString:passWordSting];
    
    if(![NSString CheckExitsWithName:nameString]) {
        NSMutableDictionary *infoDic;
        if(UserValue(@"namePsdInfo")) {
            infoDic = [NSMutableDictionary dictionaryWithDictionary:UserValue(@"namePsdInfo")];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"namePsdInfo"];
        } else {
            infoDic = [NSMutableDictionary dictionary];
        }
        
        [infoDic setValue:codeString forKey:nameString];
        UserSetValueForKey(infoDic, @"namePsdInfo");
    } else {
        [NSString changeDataWithName:nameString andPassWordString:passWordSting];
    }
}

+ (void)deleteDataWithName:(NSString *)name
{
    if([NSString CheckExitsWithName:name]) {
        NSMutableDictionary *infoDic;
        infoDic = [NSMutableDictionary dictionaryWithDictionary:UserValue(@"namePsdInfo")];
        [infoDic removeObjectForKey:name];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"namePsdInfo"];
        UserSetValueForKey(infoDic, @"namePsdInfo");
    }
}


+ (void)changeDataWithName:(NSString *)nameString andPassWordString:(NSString *)passWordString
{
    if([NSString CheckExitsWithName:nameString]) {
        
        NSMutableDictionary *infoDic;
        infoDic = [NSMutableDictionary dictionaryWithDictionary:UserValue(@"namePsdInfo")];
        NSString *codeString = [NSString codeBaseStringWithString:passWordString];
        [infoDic setValue:codeString forKey:nameString];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"namePsdInfo"];
        UserSetValueForKey(infoDic, @"namePsdInfo");
    }
}


+ (NSString *)getDataWithName:(NSString *)name
{
    if([NSString CheckExitsWithName:name]) {
        
        NSMutableDictionary *infoDic;
        infoDic = [NSMutableDictionary dictionaryWithDictionary:UserValue(@"namePsdInfo")];
        return [NSString decodeBaseStringWithString:infoDic[name]];

    } else {
        
        return nil;
    }
}

@end
